package com.chinaunicom.emergency.action;

import com.chinaunicom.emergency.annotation.Permission;
import com.chinaunicom.emergency.model.Dictionary;
import com.chinaunicom.emergency.model.Logs;
import com.chinaunicom.emergency.repository.LogsRepository;
import com.chinaunicom.emergency.service.LogsService;
import com.chinaunicom.emergency.util.Assert;
import com.chinaunicom.emergency.exception.CheckException;
import com.chinaunicom.emergency.repository.DictionaryRepository;
import com.chinaunicom.emergency.repository.UsersRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author liliang
 * @Date 2019/12/18 15:22
 * @Version 1.0
 */
@RestController
@Api(tags = {"日志管理"})
@RequestMapping("/api/logs")
@Log4j2
@RefreshScope
public class LogsAction extends BaseAction {
    @Autowired
    LogsRepository logsRepository;
    @Autowired
    LogsService logsService;

    @Autowired
    UsersRepository usersRepository;
    
    @Autowired
    DictionaryRepository dictionaryRepository;

    @ApiOperation("日志新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("logs:add")
    @PostMapping(value = "/add")
    public Object add(@RequestBody Logs logs) throws CheckException {
        Assert.isBlank(logs.getLogDescribe(), "日志描述不能为空");
        Assert.isBlank(logs.getLogType(), "日志类型不能为空");

        logs.setIsSoftDel(0);
        logs.setCreateBy(getCurrUserId());
        logs.setCreateTime(new Date());
        logsRepository.save(logs);
        return success();
    }

    

    @ApiOperation("分页查看日志列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("logs:page")
    @GetMapping(value = "/page")
    public Object findPage(@RequestParam(value = "limit", required = false) Integer limit,
                           @RequestParam(value = "page", required = false) Integer page,
                           @RequestParam(value = "logDescribe", required = false) String logDescribe,
                           @RequestParam(value = "logType", required = false) String logType,
                           @RequestParam(value = "createUserName", required = false) String createUserName,
                           @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                           @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate
    ) throws Exception {
        limit = limit == null ? 10 : limit;
        page = page == null ? 1 : page;
        if(null == endDate){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            endDate = sdf.parse(sdf.format(new Date()));
        }
        Calendar c = Calendar.getInstance();
        c.setTime(endDate);
        c.add(Calendar.DAY_OF_MONTH,1);
        endDate = c.getTime();
        if(StringUtils.isBlank(logDescribe)){
            logDescribe = "";
        }
        if(StringUtils.isBlank(logType)){
            logType = "";
        }
        if(StringUtils.isBlank(createUserName)){
            createUserName = "";
        }
        Page<Logs> pages =  logsRepository.findPageByQuery(0,logDescribe,logType,createUserName,startDate,endDate, PageRequest.of(page-1, limit));
        if(null != pages && !CollectionUtils.isEmpty(pages.getContent())){
            for (Logs logs : pages.getContent()){
                setLogsExtend(logs);
            }
        }
        return page(pages);
    }
    
    private void setLogsExtend(Logs logs) {
        if(null != logs){
            if(StringUtils.isNotBlank(logs.getCreateBy())){
                logs.setCreateUserName(getUserName(logs.getCreateBy()));
            }
            	
          }
        if(null != logs && StringUtils.isNotEmpty(logs.getLogType())) {
        	Dictionary dictionary = dictionaryRepository.findByDicCodeAndIsSoftDel(logs.getLogType(), 0);
        	if(dictionary != null && StringUtils.isNotEmpty(dictionary.getDicValue())) {
        		logs.setLogTypeStr(dictionary.getDicValue());
        	}
        }
           

    }

    /**
     * 根据字典表pid获取字典值
     * @param pid
     * @return
     */
    private String getDicValueByPid(String pid){
        Dictionary dictionary = dictionaryRepository.findByPidAndIsSoftDel(pid,0);
        return null == dictionary ? null : dictionary.getDicValue();
    }

}
